<template>
  <el-dialog title="导入Excel(.xlsx文件)" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
    <el-row :gutter="4">
      <el-col :span="20">
        <el-upload
          ref="upload"
          :action="action"
          :headers="headers"
          :on-success="onSuceess"
          :on-error="onError"
          :on-change="onUploadChange"
          :auto-upload="false"
        >
          <el-button slot="trigger" type="primary" :loading="isSubmitLoading">选择文件</el-button>
          <el-button type="success" :loading="isSubmitLoading" :disabled="uploadDisabled" @click="submitUpload">开始上传</el-button>
          <a download :href="downloadUrl">单击下载模板</a>
          <div slot="tip" class="el-upload__tip">请务必按照模板的格式导入，否则无法导入或导入数据不正确</div>
        </el-upload>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">关闭</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from "@/utils/auth/token";

export default {
  data() {
    return {
      dialogVisible: false,
      isSubmitLoading: false,
      uploadDisabled: true,
      downloadUrl: process.env.VUE_APP_BASE_API + "/tools/用户导入模板表.xlsx",
      action: process.env.VUE_APP_BASE_API + "/Upload/UploadUsers"
    };
  },
  computed: {
    headers() {
      var headers = {};
      headers["Authorization"] = getToken();
      return headers;
    }
  },
  methods: {
    show() {
      this.isSubmitLoading = false;
      this.dialogVisible = true;
    },
    submitUpload() {
      this.isSubmitLoading = true;
      this.$refs.upload.submit();
    },
    onUploadChange(file, fileList) {
      const fileName = file.name;
      const fileSize = file.size;
      if (fileName.indexOf(".xlsx") === -1) {
        this.$refs.upload.clearFiles();
        this.$message.error("只允许上传.xlsx文件!");
        return false;
      }
      if (fileSize > 1024 * 1024 * 10) {
        this.$refs.upload.clearFiles();
        this.$message.error("上传文件大小不能超过 10MB!");
        return false;
      }
      if (fileList.length > 0) {
        this.uploadDisabled = false;
      }
    },
    onSuceess(response, file, fileList) {
      if (response && response.success) {
        this.$message({ message: response.result, type: "success" });
        this.$emit("save");
      } else {
        var message = (response && response.error && response.error.message) || "上传出错，请重新上传";
        this.$message({ message: message, type: "error" });
      }
      this.isSubmitLoading = false;
      this.uploadDisabled = true;
    },
    onError(err, file, fileList) {
      if (err) {
        this.$message({ message: "上传失败，请稍候再试", type: "error" });
        this.isSubmitLoading = false;
      }
    },
    close() {
      this.$refs.upload.clearFiles();
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    }
  }
};
</script>
